<?php

namespace app\admin\model\article;

use think\Model;


class Message extends Model
{

    

    

    // 表名
    protected $name = 'article_message';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];


    /**
     * 获取列表
     * @param object $user 用户
     */
    public function getList($condition = [],$user = null,$is_paginate = 1, $limit = 15){
        $articleSeeModel = new ArticleSee();
        $list = self::where($condition)
            ->where(function($query)use ($user){
                if(!$user){
                    $user_id = 0;
                }else{
                    $user_id = $user["id"];
                }
                $query->where(function ($query1) use ($user_id) {
                    $query1->where(["type" => Article::TYPE_MESSAGE,"user_id"=>0]);
                })->whereOr(function ($query2) use ($user_id) {
                    $query2->where(["user_id"=>$user_id]);
                });
            })
            ->field("id, title,des,type,data_id")
            ->order("id", "desc");

        if($is_paginate){
            $list = $list->paginate();
        }else{
            $list = $list->limit($limit)->select();
        }

//        dump($this->getLastSql());exit;
        foreach ($list as $key => $value) {
//            $value["image"] =  deal_img_url($value["image"]);
            $value["is_see"] =  $articleSeeModel->checkSee($value["id"],  $value["type"], $user);
            $value["createtime"] = date("Y-m-d H:i:s", $value["createtime"]);
        }
        return $list;
    }

    /**
     * 获取详情
     * @param object $user 用户
     *
     */
    public function getInfo($condition = [],$user = null) {
        $info = self::where($condition)->find();
        if(!$info){
            exception("未找到该文章");
        }
//        $info["image"] = deal_img_url($info["image"]);
        $info["createtime"] = date("Y-m-d H:i:s", $info["createtime"]);
        //检测是否已读  未读的话 加一条记录
        $articleSeeModel = new ArticleSee();
        if(!$articleSeeModel->checkSee($info["id"], $info["type"], $user)){
            $articleSeeModel->addSee($info,$info["type"],$user);
        }
        return $info;
    }

    /*
     * 用户消息
     * */
    public function addUserMessage($data){
        $saveData = [
            "type" => $data['type'],
            "user_id" => $data['user_id'],
            "title" => $data['title'],
            "des" => $data['des']??'',
            "content" => $data['content']??"",
            "data_id" => $data['data_id']??0,
        ];
        $this->save($saveData);
    }



}
